package com.ihome.android.market2.adapter;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

public class ViewPagerAdapter extends PagerAdapter {

	private final FragmentManager	mFragmentManager;
	private FragmentTransaction		mCurTransaction	= null;

	public List<Fragment>			mListFrag;

	public ViewPagerAdapter(FragmentManager fm, List<Fragment> mListFrag) {
		mFragmentManager = fm;
		this.mListFrag = mListFrag;
	}

	/**
	 * 该方法将返回所包含的 Item总个数。为了实现一种循环滚动的效果，返回了基本整型的最大值，这样就会创建很多的Item,
	 * 其实这并非是真正的无限循环。
	 */
	@Override
	public int getCount() {
		return Integer.MAX_VALUE;
	}

	/**
	 * 判断出去的view是否等于进来的view 如果为true直接复用
	 */
	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	/**
	 * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来，就是position，
	 * 因为mImageViewList只有五条数据，而position将会取到很大的值， 所以使用取余数的方法来获取每一条数据项。
	 */
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {

		Fragment fragment = (Fragment) object;

		if (mCurTransaction == null) {
			mCurTransaction = mFragmentManager.beginTransaction();
		}

		mCurTransaction.remove(fragment);
	}

	/**
	 * 创建一个view，
	 */
	@Override
	public Object instantiateItem(ViewGroup container, int position) {

		if (mCurTransaction == null) {
			mCurTransaction = mFragmentManager.beginTransaction();
		}

		Fragment f = mListFrag.get(position % mListFrag.size());
		mCurTransaction.add(container.getId(), f);

		return f;
	}

	@Override
	public void finishUpdate(ViewGroup container) {
		if (mCurTransaction != null) {
			mCurTransaction.commitAllowingStateLoss();
			mCurTransaction = null;
			mFragmentManager.executePendingTransactions();
		}
	}
}